﻿using HCMS.CommonDtos;
using HCMS.Entities.Manage;
using HCMS.Extensions;
using HCMS.IRepositories.Manage;
using HCMS.IServices.Manage;
using HCMS.Repositories.Manage;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;

namespace HCMS.Services.Manage
{
    /// <summary>
    /// 管理 菜单
    /// </summary>
    public class MenuAppService : CommonAppService<ManageDbContext, Menu>, IMenuAppService
    {
        private readonly IRepository<Menu> baseMenuRepository;
        private readonly IMenuRepository menuRepository;

        public MenuAppService(
            IRepository<Menu> baseMenuRepository,
            IMenuRepository menuRepository
            ) : base(baseMenuRepository)
        {
            this.baseMenuRepository = baseMenuRepository;
            this.menuRepository = menuRepository;
        }

        /// <summary>
        /// 管理 列表
        /// </summary>
        /// <param name="searchArgs">搜索 参数</param>
        /// <param name="pager">分页 参数</param>
        /// <returns></returns>
        public async Task<ListPagerDto<Menu>> ManageList(SearchArgsDto searchArgs, PagerArgsDto pager)
        {
            var result = await menuRepository.ManageList(searchArgs, pager);
            return result;
        }

        /// <summary>
        /// 菜单 树
        /// </summary>
        /// <param name="status">状态</param>
        /// <returns></returns>
        public async Task<object> GetAllTree(int status = 9999)
        {
            return await menuRepository.GetAllTree(status);
        }

        /// <summary>
        /// 判断菜单是否重复
        /// </summary>
        /// <remarks>
        /// 不允许创建重复的菜单
        /// </remarks>
        /// <param name="id">当前的菜单 Id</param>
        /// <param name="controllerName">控制器 名称</param>
        /// <param name="actionName">方法 名称</param>
        /// <returns>true：重复菜单，false：不存在重复</returns>
        public async Task<bool> HasRepeat(int id, string controllerName, string actionName)
        {
            if (string.IsNullOrWhiteSpace(controllerName) || string.IsNullOrWhiteSpace(actionName)) { return false; }

            controllerName = controllerName.Trim();
            actionName = actionName.Trim();

            if (id == 0)
            {
                var result = await BaseFirstOrDefaultAsync(t => t.ControllerName.Trim() == controllerName && t.ActionName.Trim() == actionName) != null;
                return result;
            }
            else
            {
                var result = await BaseFirstOrDefaultAsync(t => t.Id != id && t.ControllerName.Trim() == controllerName && t.ActionName.Trim() == actionName) != null;
                return result;
            }
        }

    }
}
